﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Script.Serialization;
using RealEstateWebsite.Models;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;


namespace RealEstateWebsite.Controllers
{
    public class HomeController : Controller
    {
        static string GetSubCategoryId;
        static string GetAddressId;
        static string GetTypepriceId;
        static float GetLatitude;
        static float GetLongtitude;
        static byte[] getImage;

        REWEntities db = new REWEntities();       

        public ActionResult Index()
        {
            var posts = db.Posts.Include("Category").Include("Address").Include("TypPrice").OrderByDescending(a=>a.Id);
            ViewData["Address"] = new SelectList(db.Addresses.Select(a => new {a.Id,a.Name,a.ParentId}).Where(a=>a.ParentId=="1"), "Id", "Name");
            return View(posts);
        }
       
        public ActionResult About()
        {
            return View();
        }

        public ActionResult Rent()
        {
            var posts = db.Posts.Include("Category").Include("Address").Where(s => s.Category.ParenId == "1").OrderByDescending(a => a.Id); 
         
            return View(posts);
        }

        public ActionResult Sell()
        {
            var posts = db.Posts.Include("Category").Include("Address").Where(s => s.Category.ParenId == "2").OrderByDescending(a => a.Id);

            return View(posts);
        }

        public ActionResult Document()
        {
            return View();
        }

        public ActionResult Create()
        {
            ViewData["Addresses"] = new SelectList(db.Addresses.Select(a => new { a.Id, a.Name, a.ParentId }).Where(a => a.ParentId == "1"), "Id", "Name");
            ViewData["MainCategories"] = new SelectList(db.Categories.Select(c => new { c.Id, c.Name, c.ParenId }).Where(c => c.ParenId == null), "Id", "Name");
            ViewData["SubCategories"] = new SelectList(db.Categories.Select(c => new { c.Id, c.Name, c.ParenId }).Where(c => c.Id == null), "Id", "Name");
            ViewData["TypePrices"] = new SelectList(db.TypPrices.Select(t => new { t.Id, t.Name, t.ParentId }).Where(t => t.Id == null), "Id", "Name");
            //ViewBag.UserId = new SelectList(db.Users, "Id", "Email");         
            return View();
        }

        [HttpPost]
        public ActionResult Create(Post post, PostImage postImage)
        {
            if (ModelState.IsValid)
            {
                post.CategoryId = GetSubCategoryId;
                post.TimeOfPost = DateTime.Now;
                post.UserId = 1;
                post.AddressId = GetAddressId;
                post.TypePriceId = GetTypepriceId;
                post.LocationLatitude = GetLatitude;
                post.LocationLongtitude = GetLongtitude;
                db.Posts.AddObject(post);
                db.SaveChanges();
                
                postImage.Image = getImage;
                postImage.PostId = db.Posts.Select(c => new { c.Id }).OrderByDescending(x => x.Id).First().Id;
                db.PostImages.AddObject(postImage);
                db.SaveChanges();

                return RedirectToAction("Index");
            }
            ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", post.CategoryId);
            ViewBag.UserId = new SelectList(db.Users, "Id", "Email", post.UserId);
            return View(post);
        }

        public string GetMainCategory(string id)
        {
            var subCategories = new SelectList(db.Categories.Select(c => new { c.Id, c.Name, c.ParenId })
                                .Where(c => c.ParenId == id).OrderBy(c => c.ParenId).ThenBy(c => c.Name), "Id", "Name");
            GetSubCategoryId = subCategories.ElementAt(0).Value;

            return new JavaScriptSerializer().Serialize(subCategories);
        }

        public string GetSubCategory(string id)
        {
            GetSubCategoryId = id;
            return (GetSubCategoryId);
        }

        public string GetTypePriceList(string id)
        {
            var typePrice = new SelectList(db.TypPrices.Select(t => new { t.Id, t.Name, t.ParentId })
                            .Where(t => t.ParentId == id).OrderBy(t => t.ParentId).ThenBy(t => t.Name), "Id", "Name");
            GetTypepriceId = typePrice.ElementAt(0).Value;
            return new JavaScriptSerializer().Serialize(typePrice);
        }

        public string GetTypePrice(string id)
        {
            GetTypepriceId = id;
            return (GetTypepriceId);
        }

        public string GetAddress(string id)
        {
            GetAddressId = id;
            return (GetAddressId);
        }

        public string GetAddressName(string id)
            
        {
            string t = id;
            var AddressName = db.Addresses.Single(g => g.Id == id);

            return new JavaScriptSerializer().Serialize("quận "+AddressName.Name+", hà nội, việt nam");
         
        }

        public float GetLocationLatitude(string id)
        {
            if (float.TryParse(id, out GetLatitude) == true)
            {
                return (GetLatitude);
            }
            else return (0);
        }

        public float GetLocationLongtitude(string id)
        {
            if (float.TryParse(id, out GetLongtitude) == true)
            {
                return (GetLongtitude);
            }
            else return (0);
        }

        public string Upload(HttpPostedFileBase fileData)
        {         
            getImage = CreateImage(fileData.InputStream);
            return "ok"; 
        }

        public static byte[] CreateImage(Stream stream)
        {
            Image img = Image.FromStream(stream);
            MemoryStream ms = new MemoryStream();
            img.Save(ms, ImageFormat.Jpeg);
            return ms.ToArray();
        }

        public ActionResult GetImage(int id)
        {
            byte[] cover = GetImageCover(id);
            if (cover != null)
                return File(cover, "image/jpg");
            return null;
        }

        public byte[] GetImageCover(int postId)
        {
            var q = from postImage in db.PostImages
                    where postImage.PostId == postId
                    select postImage.Image;
            return q.FirstOrDefault();
        }        
    }
}
